#!/bin/sh
#desc: Do some cron-programmed tasks
#package:oddiscovery
#type:reserved

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

BIN_PATH=/usr/local/opendomo/discovery
CNF_PATH=/etc/opendomo/discovery/services
IP=`/sbin/ifconfig eth0 | grep 'inet addr' | cut -d ':' -f2 | cut -d ' ' -f1`

# We use unsafe semaphores, but there are not race conditions
INSTANCE=/var/run/processServices.status
RUNNING=`cat $INSTANCE` 2>/dev/null

# Read or create instance file
if ! test -e $INSTANCE
then
   echo 0 > $INSTANCE
	chown admin:admin $INSTANCE
   RUNNING=0
else
   RUNNING=`cat $INSTANCE`   
fi

# If is running, exit
if [ "$RUNNING" != "0" ]
then
   echo 1 > $INSTANCE
   exit 0
fi


# Now, it is running!
echo 1 > $INSTANCE

# Generate cofiguration file for local services
/bin/logevent notice oddiscovery "Gathering local services"
$BIN_PATH/getLocalServices.sh > $CNF_PATH


# Generate configuration file for remote services
touch /var/opendomo/oddiscovery-agentlist 
for IP in `cat /var/opendomo/oddiscovery-agentlist | cut -f1`
do
	if grep -q $IP /home/admin/.ssh/known_hosts 2>/dev/null
   then
		/bin/logevent notice oddiscovery "Gathering services from [$IP]"
		#rm -f  $CNF_PATH/$IP-services.remote
		#FIXME Instead of this, use a remote call of getLocalServices.sh. One script less to mantain!
		$BIN_PATH/getRemoteServices.sh $IP | sed -e "s/localhost/$IP/g" \
		| grep -v "#" >> $CNF_PATH
	fi
done

# Create wrapper scripts
/bin/logevent notice oddiscovery "Creating wrapper scripts [start]"
$BIN_PATH/createWrapperScripts.sh $CNF_PATH mute 2> /dev/null
/bin/logevent notice oddiscovery "Creating wrapper scripts [end]"


# Now, it is stopped!
echo 0 > $INSTANCE



